package com.zs.leymovie.utils;

import android.widget.BaseAdapter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.zs.leymovie.bean.MovieDataEntity;
import com.zs.leymovie.constants.UrlConstants;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collection;
import java.util.List;

/**
 * Created by Administrator on 2015/8/13 0013.
 */
public class HttpHelper {
    private HttpUtils utils;
    private static HttpHelper helper = null;
    private HttpHandler handler = null;
    private static int STATUS_OK = 1;

    private HttpHelper() {
        utils = new HttpUtils();

    }

    public static HttpHelper getInstance() {
        if (helper == null) {
            helper = new HttpHelper();
        }
        return helper;
    }

    public <T> HttpHandler get(String url, final List<T> list, final BaseAdapter adapter, final PullToRefreshListView view, final TypeReference typeReference) {
        handler = utils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                view.onRefreshComplete();
                String info = (String) responseInfo.result;
                String str = null;
                try {
                    JSONObject object = new JSONObject(info);
                    str = object.get("data").toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                MovieDataEntity entity = (MovieDataEntity) JSON.parseObject(str, typeReference);
                list.addAll((Collection<? extends T>) entity.getMovie_data());
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onFailure(HttpException e, String s) {
                view.onRefreshComplete();
                UrlConstants.getPrompt();
            }
        });
        return handler;
    }
}
